const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const app = express();
const port = 3001;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 添加请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  console.log('请求体:', req.body);
  next();
});

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'movie_recommendation'
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

// 测试数据库连接
async function testDatabaseConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    connection.release();
  } catch (error) {
    console.error('数据库连接失败:', error);
    process.exit(1);
  }
}

// JWT密钥
const JWT_SECRET = 'your-secret-key';

// 初始化管理员账号
async function initAdmin() {
  try {
    // 先删除现有的管理员账号
    await pool.query('DELETE FROM users WHERE username = ?', ['admin']);
    
    // 创建新的管理员账号
    const hashedPassword = await bcrypt.hash('admin123', 10);
    await pool.query(
      'INSERT INTO users (username, password, is_admin) VALUES (?, ?, ?)',
      ['admin', hashedPassword, 1]
    );
    console.log('管理员账号创建成功');
  } catch (error) {
    console.error('初始化管理员账号失败:', error);
  }
}

// 验证管理员token的中间件
const authenticateAdmin = async (req, res, next) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) {
      return res.status(401).json({ message: '未提供认证令牌' });
    }

    const decoded = jwt.verify(token, JWT_SECRET);
    if (!decoded.isAdmin) {
      return res.status(403).json({ message: '需要管理员权限' });
    }

    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ message: '无效的认证令牌' });
  }
};

// 用户注册
app.post('/api/register', async (req, res) => {
  try {
    const { username, password } = req.body;

    if (!username || !password) {
      return res.status(400).json({ message: '用户名和密码不能为空' });
    }

    // 检查用户名是否已存在
    const [existingUsers] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
    if (existingUsers.length > 0) {
      return res.status(400).json({ message: '用户名已存在' });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建新用户
    await pool.query(
      'INSERT INTO users (username, password, is_admin) VALUES (?, ?, ?)',
      [username, hashedPassword, 0]
    );

    res.status(201).json({ message: '注册成功' });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 管理员登录
app.post('/api/admin/login', async (req, res) => {
  console.log('收到管理员登录请求:', req.body);
  try {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({ message: '用户名和密码不能为空' });
    }

    // 先查询用户
    const [rows] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
    console.log('查询结果:', rows);
    
    if (rows.length === 0) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const user = rows[0];
    
    // 验证是否是管理员
    if (!user.is_admin) {
      return res.status(401).json({ message: '该账号不是管理员账号' });
    }

    // 验证密码
    const isValid = await bcrypt.compare(password, user.password);
    console.log('密码验证结果:', isValid);
    
    if (!isValid) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const token = jwt.sign(
      { id: user.id, username: user.username, isAdmin: true },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({ token });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 普通用户登录
app.post('/api/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    const [rows] = await pool.query('SELECT * FROM users WHERE username = ? AND is_admin = 0', [username]);
    
    if (rows.length === 0) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const user = rows[0];
    const isValid = await bcrypt.compare(password, user.password);
    
    if (!isValid) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const token = jwt.sign(
      { id: user.id, username: user.username, isAdmin: false },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({ token });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取统计数据
app.get('/api/admin/stats', authenticateAdmin, async (req, res) => {
  try {
    const [userCount] = await pool.query('SELECT COUNT(*) as count FROM users');
    const [movieCount] = await pool.query('SELECT COUNT(*) as count FROM movies');
    const [ratingCount] = await pool.query('SELECT COUNT(*) as count FROM ratings');

    res.json({
      totalUsers: userCount[0].count,
      totalMovies: movieCount[0].count,
      totalRatings: ratingCount[0].count
    });
  } catch (error) {
    console.error('获取统计数据错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户列表
app.get('/api/admin/users', authenticateAdmin, async (req, res) => {
  try {
    const [users] = await pool.query('SELECT id, username, created_at FROM users WHERE is_admin = 0');
    res.json(users);
  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除用户
app.delete('/api/admin/users/:id', authenticateAdmin, async (req, res) => {
  try {
    const userId = req.params.id;
    await pool.query('DELETE FROM users WHERE id = ? AND is_admin = 0', [userId]);
    res.json({ message: '用户删除成功' });
  } catch (error) {
    console.error('删除用户错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取电影列表（带分页）
app.get('/api/movies', async (req, res) => {
  try {
    const start = parseInt(req.query.start) || 0;
    const count = parseInt(req.query.count) || 20;

    const [movies] = await pool.query('SELECT * FROM movies LIMIT ?, ?', [start, count]);
    res.json(movies);
  } catch (error) {
    console.error('获取电影列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取电影列表
app.get('/api/admin/movies', authenticateAdmin, async (req, res) => {
  try {
    const [movies] = await pool.query('SELECT * FROM movies');
    res.json(movies);
  } catch (error) {
    console.error('获取电影列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除电影
app.delete('/api/admin/movies/:id', authenticateAdmin, async (req, res) => {
  try {
    const movieId = req.params.id;
    await pool.query('DELETE FROM movies WHERE id = ?', [movieId]);
    res.json({ message: '电影删除成功' });
  } catch (error) {
    console.error('删除电影错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取评分列表
app.get('/api/admin/ratings', authenticateAdmin, async (req, res) => {
  try {
    const [ratings] = await pool.query(`
      SELECT r.*, u.username, m.title 
      FROM ratings r 
      JOIN users u ON r.user_id = u.id 
      JOIN movies m ON r.film_id = m.id
    `);
    res.json(ratings);
  } catch (error) {
    console.error('获取评分列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除评分
app.delete('/api/admin/ratings/:id', authenticateAdmin, async (req, res) => {
  try {
    const ratingId = req.params.id;
    await pool.query('DELETE FROM ratings WHERE id = ?', [ratingId]);
    res.json({ message: '评分删除成功' });
  } catch (error) {
    console.error('删除评分错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新管理员密码
app.put('/api/admin/settings/password', authenticateAdmin, async (req, res) => {
  try {
    const { password } = req.body;
    const hashedPassword = await bcrypt.hash(password, 10);
    
    await pool.query(
      'UPDATE users SET password = ? WHERE id = ?',
      [hashedPassword, req.user.id]
    );
    
    res.json({ message: '密码更新成功' });
  } catch (error) {
    console.error('更新密码错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取单个电影详情
app.get('/api/movies/:id', async (req, res) => {
  try {
    const movieId = req.params.id;
    const [rows] = await pool.query('SELECT * FROM movies WHERE id = ?', [movieId]);

    if (rows.length > 0) {
      const movie = rows[0];

      // 格式化导演数据
      movie.directors = movie.director ? [{ name: movie.director, id: movie.director_id || null }] : [];

      // 格式化演员数据
      movie.casts = movie.cast ? movie.cast.split(',').map(name => ({ name: name.trim(), id: null })) : [];

      // 格式化 genres (类型) 数据
      movie.genres = movie.genres ? movie.genres.split(',').map(genre => genre.trim()) : [];

      // 格式化评分数据
      movie.rating = {
        max: 10, // 根据豆瓣API习惯，通常为10
        average: parseFloat(movie.average_rating) || 0,
        stars: (parseFloat(movie.average_rating) * 5).toFixed(0) // 将5星制转换为10星制 (如果前端使用50表示5星，则需要乘以10)
      };
      
      // 确保 images 字段存在并有 large 属性
      movie.images = {
          large: movie.image_url || ''
      };
      
      // 提取上映年份
      movie.year = movie.release_date ? movie.release_date.substring(0, 4) : '';

      res.json(movie);
    } else {
      res.status(404).json({ message: '未找到该电影' });
    }
  } catch (error) {
    console.error('获取电影详情失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 添加新电影 (管理员权限)
app.post('/api/admin/movies', authenticateAdmin, async (req, res) => {
  try {
    const { title, original_title, director, cast, genres, image_url, average_rating, wish_count, summary, release_date } = req.body;

    if (!title || !image_url) {
      return res.status(400).json({ message: '电影标题和海报URL不能为空' });
    }

    const [result] = await pool.query(
      'INSERT INTO movies (title, original_title, director, cast, genres, image_url, average_rating, wish_count, summary, release_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [title, original_title, director, cast, genres, image_url, parseFloat(average_rating) || 0, parseInt(wish_count) || 0, summary, release_date]
    );

    res.status(201).json({ message: '电影添加成功', movieId: result.insertId });
  } catch (error) {
    console.error('添加电影失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 启动服务器
async function startServer() {
  try {
    await testDatabaseConnection();
    await initAdmin();
    
    app.listen(port, '0.0.0.0', () => {
      console.log(`服务器运行在 http://0.0.0.0:${port}`);
      console.log('本地访问地址: http://localhost:3001');
      console.log('局域网访问地址: http://192.168.1.206:3001');
    }).on('error', (error) => {
      console.error('服务器启动失败:', error);
      process.exit(1);
    });
  } catch (error) {
    console.error('服务器初始化失败:', error);
    process.exit(1);
  }
}

startServer(); 